<template>
  <div class="zzddj">
    <DaoHanginPage/>
    
    <!-- 添加农产品信息 -->
    <div class="area-info">
      <h3 class="title">添加农产品</h3>
      <el-form :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="form-item">
              <label class="form-label">产品名称 <span class="required">*</span></label>
              <el-select v-if="!permitLoadError && permitProductList.length > 0" v-model="form.productId" placeholder="请选择产品">
                <el-option 
                  v-for="item in permitProductList" 
                  :key="item.productId" 
                  :label="item.productName" 
                  :value="item.productId" 
                />
              </el-select>
              <el-input v-else v-model="form.productId" placeholder="请输入产品ID（准许产品列表加载失败）" />
              <div v-if="permitLoadError" style="color: #f56c6c; font-size: 12px; margin-top: 4px;">
                准许产品列表加载失败，请手动输入产品ID
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="form-item">
              <label class="form-label">产地 <span class="required">*</span></label>
              <el-select 
                v-model="form.areaId" 
                placeholder="请选择产地"
                filterable
                :disabled="areaLoadError"
              >
                <el-option
                  v-for="item in areaList"
                  :key="item.areaId"
                  :label="item.areaName"
                  :value="item.areaId"
                />
              </el-select>
              <div v-if="areaLoadError" style="color: #f56c6c; font-size: 12px; margin-top: 4px;">
                产地列表加载失败，请手动输入产地ID
              </div>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <div class="form-item">
              <label class="form-label">计划开始时间 <span class="required">*</span></label>
              <el-date-picker clearable
                v-model="form.beginTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择计划开始时间">
              </el-date-picker>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="form-item">
              <label class="form-label">计划结束时间 <span class="required">*</span></label>
              <el-date-picker clearable
                v-model="form.reapTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择计划结束时间">
              </el-date-picker>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <div class="form-item">
              <label class="form-label">作物昵称</label>
              <el-input v-model="form.cropName" placeholder="请输入作物昵称" />
            </div>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计总产量" required>
              <div style="display: flex; gap: 10px;">
                <el-form-item prop="estimatedTotalYield" style="flex: 1; margin-bottom: 0;">
                  <el-input v-model="form.estimatedTotalYield" placeholder="请输入预计总产量" />
                </el-form-item>
                <el-form-item prop="yieldUnit" style="width: 120px; margin-bottom: 0;">
                  <el-select v-model="form.yieldUnit" placeholder="请选择产量单位">
                    <el-option label="吨" value="吨" />
                    <el-option label="千斤" value="千斤" />
                    <el-option label="斤" value="斤" />
                  </el-select>
                </el-form-item>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="form-item">
              <label class="form-label">种植面积 <span class="required">*</span></label>
              <el-input v-model="form.plantingAravage" placeholder="请输入种植面积" />
            </div>
          </el-col>
        </el-row>
      </el-form>
      <el-row justify="end">
        <el-col :span="3">
          <button @click="submitForm" class="btn2">提交</button>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import DaoHanginPage from '@/components/ncpsy/ZSPT/DaoHanginPage/DaoHanginPage.vue';
import { ref, onMounted, reactive, toRefs } from 'vue';
import { addProduct } from '@/api/ncpsy/management/product';
import { listArea } from '@/api/ncpsy/management/area';
import { listPermit } from '@/api/ncpsy/management/permit';
import useUserStore from '@/store/modules/user';
import { ElMessage } from 'element-plus';

const userStore = useUserStore();
const permitProductList = ref([]);
const permitLoadError = ref(false);
const areaList = ref([]);
const areaLoadError = ref(false);

const data = reactive({
  form: {
    productId: null,
    areaId: null,
    userId: userStore.id,
    status: '正常',
    beginTime: null,
    reapTime: null,
    cropName: null,
    estimatedTotalYield: null,
    totalYield: null,
    yieldUnit: '斤',
    plantingAravage: null,
    hash: null
  },
  rules: {
    productId: [{ required: true, message: "产品名称不能为空", trigger: "change" }],
    areaId: [{ required: true, message: "产地不能为空", trigger: "change" }],
    beginTime: [{ required: true, message: "计划开始时间不能为空", trigger: "blur" }],
    estimatedTotalYield: [{ required: true, message: "预计总产量不能为空", trigger: "blur" }],
    yieldUnit: [{ required: true, message: "产量单位不能为空", trigger: "change" }],
    plantingAravage: [{ required: true, message: "种植面积不能为空", trigger: "blur" }],
  }
});

const { form, rules } = toRefs(data);

onMounted(() => {
  loadPermitProducts();
  loadAreaList();
});

const loadPermitProducts = async () => {
  try {
    const query = {
      auditStatus: '审核通过',
      userId: userStore.id
    };
    const response = await listPermit(query);
    if (response.rows && response.rows.length > 0) {
      permitProductList.value = response.rows.map(item => ({
        productId: item.productId,
        productName: item.productName
      }));
    } else {
      permitProductList.value = [];
      ElMessage.warning('暂无审核通过的准许产品');
    }
  } catch (error) {
    console.error('获取准许产品列表失败:', error);
    ElMessage.error('获取准许产品列表失败: ' + (error.message || '未知错误'));
    permitProductList.value = [];
    permitLoadError.value = true;
  }
};

const loadAreaList = async () => {
  try {
    const queryParams = {
      pageNum: 1,
      pageSize: 100,
      userId: userStore.id,
      areaStatus: '在用'
    };
    const response = await listArea(queryParams);
    if (response.code === 200) {
      areaList.value = response.rows;
    } else {
      areaLoadError.value = true;
    }
  } catch (error) {
    console.error('获取产地列表失败:', error);
    ElMessage.error('获取产地列表失败: ' + (error.message || '未知错误'));
    areaLoadError.value = true;
  }
};

const submitForm = async () => {
  try {
    await addProduct(form.value);
    ElMessage.success("添加成功");
    reset();
  } catch (error) {
    ElMessage.error("添加失败：" + error.message);
  }
};

const reset = () => {
  form.value = {
    productId: null,
    areaId: null,
    userId: userStore.id,
    status: '正常',
    beginTime: null,
    reapTime: null,
    cropName: null,
    estimatedTotalYield: null,
    totalYield: null,
    yieldUnit: '斤',
    plantingAravage: null,
    hash: null
  };
};
</script>

<style scoped>
.zzddj{
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.area-info {
  background-color: #ffffff;
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 2px 10px rgba(209, 209, 209, 0.3);
  margin-bottom: 20px;
}

.title {
  font-size: 24px;
  font-weight: 600;
  text-align: left;
  margin-bottom: 25px;
  color: #303133;
  border-bottom: 2px solid #e4e7ed;
  padding-bottom: 15px;
}

.form-item {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  text-align: left;
  margin-bottom: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #606266;
}

.required {
  color: #f56c6c;
}

.btn2{
  font-size: 16px;
  border: none;
  width: 120px;
  height: 40px;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #2e7d32;
  color: #ffffff;
}

.btn2:hover {
  background-color: #1f5e23;
}
</style>